package com.ligq.h265toupinpush.call

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.ligq.common.utils.PermissionUtils
import com.ligq.h265toupinpush.R

class CallActivity : AppCompatActivity() {
    private lateinit var localPreview: LocalSurfaceView
    private lateinit var remotePreview: SurfaceView
    private lateinit var receiveSocket: SocketLive
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_call)
        initView()
    }

    private fun initView() {
        localPreview = findViewById(R.id.lsu_preview)
        remotePreview = findViewById(R.id.sv_remote)
        remotePreview.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                Log.d(TAG, "surfaceCreated: height=${remotePreview.measuredHeight}")
                val player = ReceiveH264Player(
                    remotePreview.measuredWidth,
                    remotePreview.measuredHeight
                )
                player.initMediaCodec(holder.surface)
                val audioPlayer = AudioRecordLive()
                receiveSocket = SocketLive(player, audioPlayer)

            }

            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {

            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {

            }

        })

    }

    fun call(view: View) {
        val socketLive = SocketLive()
        localPreview.startCapture(socketLive)
        PermissionUtils.checkPermission(
            this,
            arrayOf(Manifest.permission.RECORD_AUDIO)
        ) {
            if (it[0] == PackageManager.PERMISSION_GRANTED) {
                val audioRecordLive = AudioRecordLive(socketLive)
                audioRecordLive.startRecord()
            } else {
                Toast.makeText(this, "no record permission", Toast.LENGTH_SHORT).show()
            }
        }

    }

    fun receive(view: View) {
        if (this::receiveSocket.isInitialized) {
            receiveSocket.receive()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        receiveSocket.close()
    }
}